package com.yxq.mdt.app.modules.publish.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.personal.bean.PublishResult;
import com.yxq.mdt.app.modules.publish.ui.bean.MainPublishBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishFileList;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishListBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishTopicInfo;
import com.yxq.mdt.app.modules.publish.ui.model.MainPublishModel;
import com.yxq.mdt.app.modules.publish.ui.presenter.IMainPublishContract;
import com.yxq.mdt.app.modules.publish.ui.presenter.MainPublishPresenter;
import com.yxq.mdt.app.modules.socialcontact.adapter.PublishVideoListAdapter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialContactAllTopicsAc;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.widgets.OssHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 发布视频
 */
public class PublishVideoActivity extends BaseActivity<MainPublishPresenter> implements IMainPublishContract.View {
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.publish_topic)
    TextView publishTopic;
    @BindView(R.id.publish_select_circle)
    LinearLayout publishSelectCircle;
    int GOTOCIRCLE = 100;
    PublishVideoListAdapter publishVideoListAdapter;
    @BindView(R.id.publish_video_recyclerView)
    RecyclerView publishVideoRecyclerView;
    List<UploadImageBean> uploadImageBeanList;
    List<LocalMedia> images;
    @BindView(R.id.publish_video_content)
    EditText publishVideoContent;
    @BindView(R.id.publish_video_btn)
    TextView publishVideoBtn;
    @BindView(R.id.publish_video_content_words)
    TextView publishVideoContentWords;
    @BindView(R.id.publish_video_content_check)
    CheckBox publishVideoContentCheck;
    @BindView(R.id.address_text)
    TextView addressText;
    private String videoPathUrl, filePath, sort = "1", class2 = "0";
    private String liftText;
    String CircleName;
    private String groupId = "", TopicOfConversation = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_video;
    }

    @Override
    public void initView() {
        if (!TextUtils.isEmpty(getIntent().getStringExtra("CircleId"))) {
            groupId = getIntent().getStringExtra("CircleId");
        }
        addressText.setText(Hawk.get(SPKey.SP_KEY_USER_ADDRESS_CITY_NAME));
        //初始化图片上传控件
        publishVideoRecyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        uploadImageBeanList = new ArrayList<>();
        uploadImageBeanList.add(new UploadImageBean());
        publishVideoListAdapter = new PublishVideoListAdapter(uploadImageBeanList);
        publishVideoRecyclerView.setAdapter(publishVideoListAdapter);
        publishVideoRecyclerView.addItemDecoration(new GridSpacingItemDecoration(1, 5, false));
        publishVideoRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        publishVideoListAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (publishVideoListAdapter.getItem(position).getItemType() == -1) {
                setPublishSelectVideo();
            } else {
                //预览视频
                PictureSelector.create(mActivity).externalPictureVideo(images.get(position).getPath());
            }
        });
        publishVideoListAdapter.setOnItemChildClickListener((adapter, view, position) -> {

            List<UploadImageBean> uploadImageBeanList = publishVideoListAdapter.getData();

            if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                uploadImageBeanList.remove(position);
                images = null;//清空数据
                //第一张不是添加图片，添加按钮
                List<UploadImageBean> temp = new ArrayList<>();
                temp.addAll(uploadImageBeanList);
                temp.add(new UploadImageBean());
                publishVideoListAdapter.setNewData(temp);

            } else {
                publishVideoListAdapter.remove(position);
                images = null;//清空数据
            }

        });

        publishSelectCircle.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(publishVideoContent.getText())) {
                if (publishVideoContent.getText().toString().contains("#")) {
                    TopicOfConversation = publishVideoContent.getText().toString().substring(publishVideoContent.getText().toString().indexOf("#"), publishVideoContent.getText().toString().lastIndexOf("#") + 1);
                    publishVideoContent.setText(liftText);
                }
                TopicOfConversation = "";
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publish", "1");
                startActivityForResult(intent, GOTOCIRCLE);
            } else {
                publishVideoContent.setHint("");
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publish", "1");
                startActivityForResult(intent, GOTOCIRCLE);
            }


        });
        //文本内容
        publishVideoContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                publishVideoBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                publishVideoBtn.setTextColor(getResources().getColor(R.color.color_font_black));
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = publishVideoContent.getText().toString();
                if (content.length() == 0) {
                    publishVideoBtn.setBackgroundResource(R.drawable.shape_btn_lin_selector);
                    publishVideoBtn.setTextColor(getResources().getColor(R.color.gray_pressed));
                } else {
                    publishVideoBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                    publishVideoBtn.setTextColor(getResources().getColor(R.color.color_font_black));
                }
                publishVideoContentWords.setText(content.length() + "/" + 1000);

            }
        });
    }


    //判断当前输入的文字跟上传的视频是否为空
    private void setContentIsNull() {
        if (images != null && images.size() > 0) {
            showLoadingDialog();
            class2 = String.valueOf(OssHelper.getVideoVoiceTime(videoPathUrl));
            @SuppressLint("AutoDispose") Disposable disposable = Observable
                    .create((ObservableOnSubscribe<String>) emitter -> {

                        File file = new File(videoPathUrl);
                        OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP + file.getName(), file.getPath()));
                        String url = OssHelper.getOssPrefixUrl(OssHelper.GS_APP, file.getName());
                        emitter.onNext(url);

                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((String s) -> {

                        filePath = s;
                        //获取阿里云返回得url
                        List<PublishFileList> lists = new ArrayList<>();
                        PublishFileList video = new PublishFileList(sort, filePath, class2);
                        lists.add(video);
                        PublishTopicInfo topicInfo;
                        //是否发布地址
                        if (publishVideoContentCheck.isChecked()) {
                            topicInfo = new PublishTopicInfo(publishVideoContent.getText().toString(), "2", groupId, "");
                        } else {
                            topicInfo = new PublishTopicInfo(publishVideoContent.getText().toString(), "2", groupId, "");
                        }
                        MainPublishBean publishBean = new MainPublishBean();
                        publishBean.setGsTopicInfo(topicInfo);
                        publishBean.setFileList(lists);
                        //发布视频
                        mPresenter.onSetDoPublishList(JSON.toJSONString(publishBean));

                    }, Throwable::printStackTrace);
        } else {
            ToastUtils.showShort("请上传视频");
        }
    }

    /**
     * 打开视频选择器
     */
    private void setPublishSelectVideo() {
        //视频
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(2 - publishVideoListAdapter.getData().size())//选择最多一个视频
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .previewVideo(true)
                .recordVideoSecond(15)
                .forResult(PictureConfig.TYPE_VIDEO);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new MainPublishPresenter(this, new MainPublishModel());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    CircleName = data.getStringExtra("CircleName");
                    liftText = publishVideoContent.getText().toString();
                    if (!TextUtils.isEmpty(data.getStringExtra("CircleName"))) {
                        publishTopic.setText(CircleName);
                    } else {
                        publishTopic.setText("");
                    }
                    TopicOfConversation = "";
                    publishVideoContent.setText(data.getStringExtra("CircleName") + liftText);
                    publishVideoContent.setSelection(publishVideoContent.getText().length());
                    break;
                case PictureConfig.TYPE_VIDEO:
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);
                    break;
                default:
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getPath());
            data.add(uploadImageBean);
        }
        List<UploadImageBean> temp = publishVideoListAdapter.getData();
        temp.remove(temp.size() - 1);
        temp.addAll(data);
        publishVideoListAdapter.setNewData(temp);
        videoPathUrl = images.get(0).getPath();
    }

    @OnClick({R.id.publish_video_btn, R.id.pub_voice_tv_user_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.publish_video_btn:
                setContentIsNull();
                break;
            case R.id.pub_voice_tv_user_agreement:
                Intent intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PUBLIC_USER_AGREEMENT);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onSetDoPublishSuccess(PublishListBean publishListBean) {
        hideLoadingDialog();
        showBottomToast("发布成功");
        new Handler().postDelayed(() -> {
            EventBus.getDefault().post(new PublishResult());
            finish();
        }, 200);
    }

    @Override
    public void onSetDoPublishFailed(String errMsg) {
        hideLoadingDialog();
        showBottomToast(errMsg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Jzvd.releaseAllVideos();
    }
}
